package com.soft.cake.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.soft.cake.mapper.CartMapper;
import com.soft.cake.pojo.Cart;
import com.soft.cake.pojo.Product;
import com.soft.cake.pojo.User;
import com.soft.cake.service.ICartService;

@Service
public class CartServiceImpl implements ICartService{
	
	@Autowired
	private CartMapper cartMapper;
	

	@Override
	public void add(Cart cart) {
		//创建一个Map集合,用来查询同一个用户的购物车有没有相同的商品
		Map<String, Integer> map = new HashMap<String, Integer>();
		map.put("pid", cart.getProduct().getProductId());
		map.put("uid", cart.getUser().getUserId());
		
		//According product and User to select a date from datebase
		//to find the cart whether exist this date
		Cart c = cartMapper.selectByProductAndUser(map);
		//购物车中没有该条记录
		if(c == null) {
		
			cartMapper.insert(cart);
		}
		//购物车中有该条数据
		else {
			//修改购物车记录中的商品数量
			c.setProductQuantity(cart.getProductQuantity()+c.getProductQuantity());
			cartMapper.updateByPrimaryKey(c);
		}
		
		
	}
	
	/**
	 * @author Bryan
	 * @description 通过主键修改数量
	 */
	@Override
	public void update(int id,int quantity) {
		Cart cart = new Cart();
		cart.setCartId(id);
		cart.setProductQuantity(quantity);
		cartMapper.updateByPrimaryKeySelective(cart);
	}

	/**
	 * @author Bryan
	 * @description 根据userId 获取该用户的购物车列表
	 * @param id
	 * @return List<Cart>
	 */
	@Override
	public List<Cart> loadList(int id) {
		//根据用户id 查询购物车列表
		List<Cart> cartList =  (List<Cart>) cartMapper.selectListByUserId(id);
		return cartList;
	}

	/* 
	 * 从购物车中删除商品
	 * @see com.soft.cake.service.ICartService#delete(java.lang.Integer)
	 * @author Bryan
	 */
	@Override
	public void delete(Integer id) {
		
		cartMapper.deleteByPrimaryKey(id);
		
	}



	
}
